#from django.core.serializers import serialize
#from django.db.models.query import QuerySet, ValuesListQuerySet
#from django.utils.safestring import mark_safe
from django.template import Library
from django.utils.safestring import mark_safe
from ..data_format.json_format import DirectorEncoder
from django.template.base import VariableDoesNotExist
import json,re


register = Library()
replace_script = re.compile('<(/script>)',flags=re.IGNORECASE)

#def jsonify(obj):
    ## 关键：把“未定义”和空字符串也当作“无值”
    #if obj is None or obj == '' or isinstance(obj, VariableDoesNotExist):
        #return ''
    #outstr = json.dumps(obj, cls=DirectorEncoder, ensure_ascii=False)
    #outstr = replace_script.sub('<" + "\\g<1>', outstr)
    #return mark_safe(outstr)

def jsonify(obj):
    if obj is None:
        return ''
    else:
        outstr=json.dumps(obj,cls=DirectorEncoder,ensure_ascii=False)
        #'<' + '/script>'
        #outstr = outstr.replace('</script>','<" + "/script>')
        #outstr = aa.sub('<" + "/script>',outstr)  # outstr.replace('</script>','<" + "/script>')
        outstr = replace_script .sub('<" + "\g<1>',outstr) 
        outstr =  mark_safe( outstr )
        
        return outstr

    #if isinstance(object, ValuesListQuerySet):
        #return mark_safe(json.dumps(list(object)))
    #if isinstance(object, QuerySet):
        #return mark_safe(serialize('json', object))
    #return mark_safe(json.dumps(object))

register.filter('jsonify', jsonify, is_safe=True)
#jsonify.is_safe = True  

def json_or(value, fallback='false'):
    #from django.template.base import VariableDoesNotExist
    if value in (None, '') or isinstance(value, VariableDoesNotExist):
        return mark_safe(fallback)  # 直接输出原样 JSON 片段
    s = json.dumps(value, cls=DirectorEncoder, ensure_ascii=False)
    s = replace_script.sub('<" + "\\g<1>', s)
    return mark_safe(s)

register.filter('json_or', json_or, is_safe=True)